package com.xz.group12306.filter;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Servlet Filter implementation class SessionValidatorFilter
 */
@WebFilter("/LoginFilter")
public class LoginFilter implements Filter {

	/**
	 * Default constructor.
	 */
	public LoginFilter() {
		// TODO Auto-generated constructor stub
	}

	/**
	 * @see Filter#destroy()
	 */
	public void destroy() {
		// TODO Auto-generated method stub
	}

	/**
	 * @see Filter#doFilter(ServletRequest, ServletResponse, FilterChain)
	 */
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
			throws IOException, ServletException {
		// TODO Auto-generated method stub
		// place your code here

		// pass the request along the filter chain

		HttpServletRequest httprequest = null;
		HttpServletResponse httpresponse = null;
		if (request instanceof HttpServletRequest) {
			httprequest = (HttpServletRequest) request;
		}
		if (response instanceof HttpServletResponse) {
			httpresponse = (HttpServletResponse) response;
		}
		if (httprequest != null) {
			if (httprequest.getRequestURI().endsWith(".css") || httprequest.getRequestURI().endsWith(".js")) {
				chain.doFilter(request, response);
				return;
			}
			if (httprequest.getRequestURI().endsWith(".jpg") || httprequest.getRequestURI().endsWith(".gif")) {
				chain.doFilter(request, response);
				return;
			}
			if (httprequest.getRequestURI().endsWith("login.html")
					|| httprequest.getRequestURI().endsWith("UserRegister.html")) {
				chain.doFilter(request, response);
				return;
			}
			if (httprequest.getRequestURI().endsWith("Servlet")) {
				chain.doFilter(request, response);
				return;
			}

			Object ouser = httprequest.getSession().getAttribute("user");
			if (ouser == null) {
				httpresponse.sendRedirect("../user/login.html");
			} else {
				chain.doFilter(request, response);
			}
		} else {

		}

	}

	/**
	 * @see Filter#init(FilterConfig)
	 */
	public void init(FilterConfig fConfig) throws ServletException {
		// TODO Auto-generated method stub
	}

}
